<?php
/**
 * Miffos framework
 * ----------------------------------------------
 *
 * Copyright (c) 2008, 2009 Martin Sadový (http://sodae.cz)
 *
 * This source file is subject to the "Miffos license" that is bundled
 * with this package in the file license.txt.
 *
 * @copyright  Copyright (c) 2008, 2009 Martin Sadový
 * @license    license.txt
 * @link       http://miffos.sodae.cz
 * @package    miffos
 * @version    $Id$
 */

class Http {

    private $request;

    public $ajax;
    
    public $safe;

    public $global = true;

    public function __construct(){
        $this->initialize();
    }


    /**
     * Initialize request data
     */
    public function initialize(){

        /* Http request */
        $request = array("get"=>&$_GET,"post"=>&$_POST,"cookie"=>&$_COOKIE,"files"=>&$_FILES);
        
        $this->safe = $request; // backup original data

        if(get_magic_quotes_gpc()){
            while (list($key, $value) = each($request)) {
                foreach($value as $k=>$v){
                    unset($request[$key][$k]);
                    if(is_array($v)){
						$request[$key][stripslashes($k)] = $v;
						$request[] = &$request[$key][stripslashes($k)];
                    }else{
                        $request[$key][stripslashes($k)] = stripslashes($v);
                    }

                }
            }
            $this->request = $request;
        }

        /*  Ajax */
        if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&$_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest'){
            $this->ajax = true;
        }else{
            $this->ajax = false;
        }
    }

    /**
     * Is call method ?
     * @param string $name
     * @return bool
     */
    public function isMethod($name){
        return isset($_SERVER['REQUEST_METHOD'])?(strcasecmp($_SERVER['REQUEST_METHOD'], $name) == 0):false;
    }



    /**
     * Is Ajax
     * @return bool
     */
    public function isAjax(){
        return $this->ajax;
    }



    /**
     * Is script call as post ?
     * @return bool
     */
    public function isPost(){
        return $this->isMethod("post");
    }



    /**
     * Return cookie(s)
     * @param string $name
     * @param mixed  $default
     * @return mixed
     */
    public function getCookie($name=null,$default=null)
    {
        return $this->_getRequest('cookie',$name, $default);
    }



    /**
     * Return post(s)
     * @param string $name
     * @param mixed  $default
     * @return mixed
     */
    public function getPost($name=null,$default=null)
    {
        return $this->_getRequest('post',$name, $default);
    }



    /**
     * Return "get(s)"
     * @param string $name
     * @param mixed  $default
     * @return mixed
     */
    public function getGet($name=null,$default=null)
    {
        return $this->_getRequest('get',$name, $default);
    }


    /**
     * Return Files
     * @param string $name
     * @param mixed  $default
     * @return mixed
     */
    public function getFile($name=null,$default=null)
    {
        return $this->_getRequest('files',$name, $default);
    }



    /**
     * Return request data
     * @param string $type
     * @param string $name
     * @param mixed $default
     * @return mixed
     */
    private function _getRequest($type,$name,$default){

        if(is_null($name)){
            return $this->request[$type];
        }elseif(isset($this->request[$type][$name])){
            return $this->request[$type][$name];
        }else{
            return $default;
        }

    }



    /**
     * Get Request Url
     * @return string
     */
    public function getRequestUrl(){
        
          $url = urldecode($_SERVER['REQUEST_URI']);
          $url = substr($url, strlen($this->getPath(true)));
          $path = '/'.basename($this->getPath());
          if($path == substr($url, 0, strlen($path)))
              $url = substr($url, strlen($path));
          return trim($url, '/\\');
    }



    /**
     * Get Path Url (with/without file name)
     * @param bool $dir
     * @return string
     */
    public function getPath($dir=false){
        return $dir?trim(dirname($_SERVER['SCRIPT_NAME']),'/').'/':$_SERVER['SCRIPT_NAME'];
    }



    /**
     * Get uri
     * @return string
     */
    public function getUri($withdir=false){
        $url = (isset($_SERVER['HTTPS'])?'https':'http').'://'.$_SERVER['SERVER_NAME'].'/';
        if($withdir){
            $dir = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
            if (!empty($dir))
                $url .= $dir.'/';
        }
        return $url;
    }


    /**
     * Return if already header were sent
     * @return bool
     */
    public function isSendHeader(){
        return headers_sent();
    }

    
    /**
     * Set header
     * @param string $name
     * @param string $value
     */
    public function setHeader($name,$value=null,$replace=true,$respone=null){
        if($this->isSendHeader())
            throw new Exception("Headers can be sent.");
        $value = (!empty($value))?':'.$value:'';
        header($name.$value,$replace,$respone);
    }


    
    /**
     * Sends a cookie
     * @param string $name
     * @param mixed  $value
     * @param int    $expire
     */
    public function setCookie($name,$value,$expire=31536000,$path='/'){
        if($this->isSendHeader())
            throw new Exception("Headers can be sent.");

        setcookie($name, $value, $expire, $path);
    }



    /**
     * Delete a cookie
     * @param string $name
     * @param mixed  $value
     * @param int    $expire
     */
    public function deleteCookie($name){
        $this->setCookie($name,false,time()-31536000);
    }



    /**
     * Redirect
     * @param string $url
     * @param int $type
     */
    public function redirect($url,$type=303){
        try{
            $this->setHeader("Location",$url,true,303);
            
        }catch(Exception $exception){
            echo '<script type="text/javascript">window.location.href="'.$url.'";</script>'.
                 '<noscript><meta http-equiv="refresh" content="0;url='.$url.'" /></noscript>';
        }
    }
}
?>